import { defineStore } from 'pinia'

interface UserName {
  access_name: string
}

export const useUserNameStore = defineStore('userName', () => {
  //ref相当于state
  const tokenJson = ref('')
  //computed相当于getter
  const nameRestaurant = computed<UserName>(() => {
    try {
      return JSON.parse(tokenJson.value || window.localStorage.getItem('userName') || '{}')
    } catch (err) {
      ElMessage.error('josn字符串格式不对,转化对象是时失败...')
      //防止window.localStorage下次再次报错，设置成空
      window.localStorage.setItem('userName', '')
      throw err
    }
  })
  //function相当于actions
  function saveUesrName(data: string) {
    tokenJson.value = data
    window.localStorage.setItem('userName', data)
  }

  return { nameRestaurant, saveUesrName }
})
